#include "TcpClient.h"

namespace mp_net
{
	void TcpClient::SetIoService(spIoService ioService)
	{
		while(!TryLock()){Pause(MPN_TCP_MTX_LOCK_DELAY);}
		TcpSession::SetIoService(ioService);
		UpdateResolver();
		Unlock();
	}

	void TcpClient::UpdateResolver()
	{
		m_resolver = new tcp::resolver(*m_ioService);
	}

	void TcpClient::ThreadInitialization()
	{
		TcpSession::ThreadInitialization();
	}

	void TcpClient::ThreadUpdate()
	{
		AsyncResolve();
		TcpSession::ThreadUpdate();
	}

	void TcpClient::ThreadShutdown()
	{
		TcpSession::ThreadShutdown();
	}

	void TcpClient::AsyncResolve()
	{
		if (!m_connected)
		{
			if (m_resolver != NULL)
			{
				m_connected = true;
				tcp::resolver::query q = tcp::resolver::query("", "2145");

				std::cout << "## Async Resolve" << "\n";

				m_resolver->async_resolve(
					q, 
					boost::bind(
					&TcpClient::AsyncResolveProc,
					this,
					boost::asio::placeholders::error,
					boost::asio::placeholders::iterator)
				);
			}
		}
	}

	void TcpClient::AsyncResolveProc(
		const boost::system::error_code& error,
		tcp::resolver::iterator endpoint_iterator)
	{

		std::cout << "## Resolving" << "\n";
		std::cout << endpoint_iterator->endpoint().port() << "\n";
		std::cout << endpoint_iterator->endpoint().address().to_string() << "\n";
		std::cout << endpoint_iterator->host_name() << "\n";

		if (error)
		{
			m_connected = false;
			std::cout << error.message() << "\n";
		}
	}

	void AsyncConnect()
	{

	}

	void AsyncResolveProc(
		const boost::system::error_code& error)
	{

	}

}